import { BrowserWindow } from "electron";
import { createNetworkSpeedMonitor, getMemoryInfo } from "../utils";

export function createDataMonitor(
  mainWindow: BrowserWindow | null,
  speedBallWindow: BrowserWindow | null = null,
) {
  let _mainWindow = mainWindow;
  let _speedBallWindow = speedBallWindow;
  let monitoringInterval: NodeJS.Timeout | null = null;

  function updateWindows(
    mainWindow: BrowserWindow | null,
    speedBallWindow: BrowserWindow | null = null,
  ) {
    _mainWindow = mainWindow;
    _speedBallWindow = speedBallWindow;
  }

  async function startMonitoring() {
    const getNetworkSpeed = await createNetworkSpeedMonitor();
    monitoringInterval = setInterval(() => {
      console.log(Date.now());
      Promise.all([getNetworkSpeed(), getMemoryInfo()])
        .then(([networkData, memoryInfo]) => {
          _mainWindow?.webContents.send("networkSpeed", networkData);
          _speedBallWindow?.webContents.send("networkSpeed", networkData);
          _mainWindow?.webContents.send("memoryInfo", memoryInfo);
          _speedBallWindow?.webContents.send("memoryInfo", memoryInfo);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    }, 2000);
  }

  function stopMonitoring() {
    if (monitoringInterval) {
      clearInterval(monitoringInterval);
      monitoringInterval = null;
    }
  }

  return {
    startMonitoring,
    stopMonitoring,
    updateWindows,
  };
}
